/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.itjisu.hongbao.core;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mobads.AdView;
import com.baidu.mobads.AdViewListener;
import com.baidu.mobads.AppActivity;
import com.baidu.mobads.InterstitialAd;
import com.baidu.mobads.InterstitialAdListener;
import com.itjisu.hongbao.R;
import com.itjisu.hongbao.constants.ConfigEntry;
import com.itjisu.hongbao.constants.GlobalConfig;
import com.itjisu.hongbao.model.RecievedRedBagEntity;
import com.itjisu.hongbao.model.RedBagEntity;
import com.itjisu.hongbao.util.MLog;
import com.itjisu.hongbao.util.ManageKeyguard;
import com.itjisu.hongbao.util.ManageScreen;
import com.itjisu.hongbao.util.NetUtils;
import com.itjisu.hongbao.util.Util;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;

import java.text.DecimalFormat;
import java.util.List;

//import com.baidu.mobads.AdView;
//import com.baidu.mobads.AdViewListener;
//import com.baidu.mobads.AppActivity;
//import com.baidu.mobads.InterstitialAd;
//import com.baidu.mobads.InterstitialAdListener;


/**
 * Starts up the task list that will interact with the AccessibilityService
 * sample.
 */
public class QiangHongBaoActivity extends Activity {

    public final static String MONEY_OF_THIS_TIME = "money";
    public final static String MONEY_FROM = "from";
    public final static String NO_MONEY_REASON = "reason";
    /**
     * An intent for launching the system settings.
     */
    private static final Intent sSettingsIntent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
    @ViewInject(R.id.status)
    private ImageView status;


    @ViewInject(R.id.mine)
    private ImageView mine;

    @ViewInject(R.id.settings)
    private ImageView settings;

    @ViewInject(R.id.share)
    private ImageView share;

    @ViewInject(R.id.about)
    private ImageView about;
    @ViewInject(R.id.vipbtn)
    private ImageView vipbtn;

//    @ViewInject(R.id.vip_expire)
//    private TextView vip_expire;
    @ViewInject(R.id.tv_title2)
    private TextView tv_title2;
    @ViewInject(R.id.tv_title3)
    private TextView tv_title3;

    private RelativeLayout parent;
    Dialog mEnableServiceHintDialog = null;
//    final String adSpaceid = "uaaHvtK250";
private RelativeLayout adContainer;
//    final String adSpaceidCp = "PuawbYAWkL";
//    IMvBannerAd bannerad;
//    IMvInterstitialAd interstitialAd;

//    FrameLayout adsParent;
//    private static AdView interstialAdView;

    private void processExtraData() {
        Intent intent = getIntent();
        float sum = 0;

        try {
            DbUtils db = DbUtils.create(this);
            List<RecievedRedBagEntity> list = db.findAll(RecievedRedBagEntity.class);
            MLog.d("processExtraData list size = " + list.size());
            for (RecievedRedBagEntity rrg : list) {
                try {
                    sum += Float.parseFloat(rrg.getCoin());
                } catch (Exception e) {
                }
            }
            db.close();
        } catch (Exception e) {

        }

        tv_title3.setText(String.format(getResources().getText(R.string.money_total_desc).toString(), new DecimalFormat("##0.00").format(sum)));

        try {
            String money = intent.getStringExtra(MONEY_OF_THIS_TIME);
            String reason = intent.getStringExtra(NO_MONEY_REASON);
            String from = intent.getStringExtra(MONEY_FROM);
            if (money.equals(RedBagEntity.DEFAULT_MONEY)) {
//                interstitialAd = Mvad.showInterstitial(this, adSpaceidCp,
//                        true);
//                if (interAd.isAdReady()){
//                    interAd.showAd(QiangHongBaoActivity.this);
//                }else {
//                    interAd.loadAd();
//                }
                if (reason.equals("")) {
                    tv_title2.setText(getResources().getText(R.string.money_result_desc));
                } else {
                    tv_title2.setText(reason);
                }

            } else {
                tv_title2.setText(String.format("抢到%s红包：%s元", from.equals("qq") ? "QQ" : "微信", money));
//                interstitialAd = Mvad.showInterstitial(this, adSpaceidCp,
//                        false);


//                if (interAd==null) {
//                    interAd = new InterstitialAd(this, adPlaceId);
////                    interstitialAd.showAds(this);
//                }else {
//                if (interAd.isAdReady()){
//                    interAd.showAd(QiangHongBaoActivity.this);
//                }else {
//                    interAd.loadAd();
//
//                }
//                    interAd.loadAd();
//                }
//                if (!User.isVip() || !User.isLogin) {
//                    if (interstialAdView != null) {
//                        interstialAdView.showInterstialAd();
//                    }
//                }
            }

        } catch (Exception e) {
        }
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        processExtraData();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        Log.e("xiaoke", "Get onCreate savedInstanceState");
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        try {
//            UpdateManager.checkNeedsUpdate(this);
        } catch (Exception e) {
            MLog.e("update fail", e);
        }
        updateVipView();


//        if (MyApplication.sdkManager == null) {
//            MyApplication.sdkManager = HuosdkManager.getInstance();
//            MyApplication.sdkManager.initSdk(this, new OnInitSdkListener() {
//                @Override
//                public void initSuccess(String code, String msg) {
//                    if (GlobalConfig.isDebug) {
//                        Log.d(GlobalConfig.TAG, "sdkManager initSuccess");
//                    }
//                    User.login(getApplicationContext(), new CallBack() {
//                        @Override
//                        public void run(String content) {
//                            mainHandler.post(new Runnable() {
//                                @Override
//                                public void run() {
//                                    if (User.vipIsExpire()) {
//                                        Util.showExpiredVipDialog(QiangHongBaoActivity.this);
//                                    }
//                                }
//                            });
//                            isLoginFinish = true;
//                        }
//                    }, new CallBack() {
//                        @Override
//                        public void run(String content) {
//                            updateVipView();
//                            isLoginFinish = true;
//                        }
//                    });
//                }
//
//                @Override
//                public void initError(String code, String msg) {
//                    updateVipView();
//                    Log.e(GlobalConfig.TAG, "sdkManager initSdk Error=" + msg + " code =" + code);
//
//                }
//            });
//        }
        setContentView(R.layout.main_layout);

//        adsParent = new FrameLayout(this);
        ViewUtils.inject(this);
       tv_title3= findViewById(R.id.tv_title3);
        tv_title2= findViewById(R.id.tv_title2);
       parent= findViewById(R.id.asparent);
//        adContainer=findViewById(R.id.adContainer);
//       bannerad = Mvad.showBanner(adContainer,
//                QiangHongBaoActivity.this, adSpaceid, false);
//        bannerad.showAds(this);

//       vip_expire= findViewById(R.id.vip_expire);
        processExtraData();

//        Util.sendPackageList(this);
//        adbanner();
//        interstitialAd();
    }

//    private AdView bannerAdView;

    public void updateVipView() {
        mainHandler.post(new Runnable() {
                             @Override
                             public void run() {
//                                 if (User.isVip() && User.isLogin) {
////                                     vip_expire.setVisibility(View.VISIBLE);
////                                     vip_expire.setText("VIP会员 " + User.getVipExpireTimeString() + "过期");
//                                     final FrameLayout banner_ad = (FrameLayout) findViewById(R.id.main_ad_banner);
////                                     if (bannerAdView != null) {
////                                         bannerAdView.clearDisappearingChildren();
////                                         bannerAdView.destroyDrawingCache();
////                                         banner_ad.removeView(bannerAdView);
////                                         bannerAdView = null;
////                                     }
////                                     if (interstialAdView != null) {
////                                         interstialAdView.clearDisappearingChildren();
////                                         interstialAdView.destroyDrawingCache();
////                                         interstialAdView = null;
////                                     }
//                                     if (getPackageName().equals("com.mogo.space")) {
//                                         TextView t = (TextView) findViewById(R.id.tv_title_vip);
//                                         t.setText("VIP:尊敬的VIP用户，点击下方\"VIP专用\"按钮，即可获取专属VIP版，专属VIP版可以防止被封号，安装后请将本应用删除。");
//                                         final ImageView imageView = (ImageView) findViewById(R.id.status);
//                                         imageView.setOnClickListener(new OnClickListener() {
//                                             boolean isrun = false;
//
//                                             @Override
//                                             public void onClick(View v) {
//                                                 if (isrun) {
//                                                     imageView.setImageResource(R.drawable.status_on);
//                                                     isrun = false;
//                                                     QiangHongBaoService.ISRUNNING = false;
//                                                 } else {
//                                                     imageView.setImageResource(R.drawable.zzq);
//                                                     QiangHongBaoService.ISRUNNING = true;
//                                                     isrun = true;
//                                                 }
////                                if (isclickone) {
////                                    if (!GlobalConfig.VIP_URL.trim().equals("")) {
////                                        GetVIP getVIP = new GetVIP(QiangHongBaoActivity.this, GlobalConfig.VIP_URL);
////                                        getVIP.showDownloadDialogAndStart();
////                                    } else {
////                                        Toast.makeText(QiangHongBaoActivity.this, "本按钮失效，请联系客服人员下载VIP专用版", Toast.LENGTH_LONG).show();
////                                    }
////                                    isclickone = false;
////                                } else {
////                                    isclickone = true;
////                                    mainHandler.postDelayed(new Runnable() {
////                                        @Override
////                                        public void run() {
////                                            isclickone = false;
////                                        }
////                                    }, 1000);
////                                }
//                                             }
//                                         });
//                                         ImageView vipdown = (ImageView) findViewById(R.id.vipdown);
//                                         vipdown.setOnClickListener(new OnClickListener() {
//                                             @Override
//                                             public void onClick(View v) {
//                                                 if (!GlobalConfig.VIP_URL.trim().equals("")) {
//                                                     GetVIP getVIP = new GetVIP(QiangHongBaoActivity.this, GlobalConfig.VIP_URL);
//                                                     getVIP.showDownloadDialogAndStart();
//                                                 } else {
//                                                     Toast.makeText(QiangHongBaoActivity.this, "本按钮失效，请联系客服人员下载VIP专用版", Toast.LENGTH_LONG).show();
//                                                 }
//                                             }
//                                         });
//                                     }
//                                 } else {
//                                     if (bannerAdView == null) {
//                                         final FrameLayout banner_ad = (FrameLayout) findViewById(R.id.main_ad_banner);
//                                         bannerAdView = new AdView(QiangHongBaoActivity.this, AdSize.Banner, GlobalConfig.Banner_ADSLOT);
//                                         banner_ad.addView(bannerAdView, new LinearLayout.LayoutParams(-1, -1));
//                                     }
//                                     vip_expire.setVisibility(View.INVISIBLE);
//                                     if (interstialAdView == null) {
//                                         interstialAdView = new AdView(QiangHongBaoActivity.this, AdSize.Interstitial, GlobalConfig.Inter_ADSLOT);
//                                     }
                                     TextView t = (TextView) findViewById(R.id.tv_title_vip);
                                     t.setText("客服交流群：");
                                     final ImageView imageView = (ImageView) findViewById(R.id.status);
                                     imageView.setOnClickListener(new OnClickListener() {
                                         boolean isrun = false;

                                         @Override
                                         public void onClick(View v) {
                                             if (isrun) {
                                                 imageView.setImageResource(R.drawable.status_on);
                                                 isrun = false;
                                                 QiangHongBaoService.ISRUNNING = false;
                                             } else {
                                                 imageView.setImageResource(R.drawable.zzq);
                                                 QiangHongBaoService.ISRUNNING = true;
                                                 isrun = true;
                                             }
                                         }
                                     });
                                     ImageView vipdown = (ImageView) findViewById(R.id.vipdown);
                                     vipdown.setOnClickListener(new OnClickListener() {
                                         @Override
                                         public void onClick(View v) {
                                           Toast.makeText(QiangHongBaoActivity.this, "VIP专用，请先充值！", Toast.LENGTH_LONG).show();
                                         }
                                     });
                                 }
                             }

//                         }

        );
    }

    Handler mainHandler = new Handler();
    public static boolean isLoginFinish = false;

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
//        IAppPay.init(this, 1, PayConfig.appid);
        ViewUtils.inject(this);

        NetUtils.postLog(GlobalConfig.getCommonInfo(GlobalConfig.RESUME_DataType).toString());
//        Util.httpPing(this, Util.SERVER_URL_ACTIVATE + Util.getCommonParam(this))

//        Log.e("xiaoke", "conf entry =" + ConfigEntry.isAccessibilityEnabled(this));
        if (!ConfigEntry.isAccessibilityEnabled(this) || !QiangHongBaoService.RUN) {
            showEnableServiceHintDialog();
        }
        ManageKeyguard.reenableKeyguard();
        ManageScreen.lightOff(this.getApplicationContext());
        if (isLoginFinish) {
            updateVipView();
        }
        boolean isOpen = ConfigEntry.getIsWeiXinOpen() || ConfigEntry.getIsQQOpen();
//        status.setBackgroundResource(isOpen ? R.drawable.status_on : R.drawable.status_off);
    }

    @Override
    protected void onDestroy() {
        com.baidu.mobads.production.BaiduXAdSDKContext.exit();
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        try {
            if (mEnableServiceHintDialog != null) {
                mEnableServiceHintDialog.dismiss();
                mEnableServiceHintDialog = null;
            }

        } catch (Exception e) {
        }
    }

    @OnClick({R.id.mine, R.id.settings, R.id.about, R.id.vipbtn, R.id.share})
    public void imgClicked(View v) {
//        final Intent intent = new Intent(this, SecondaryActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        switch (v.getId()) {

            case R.id.mine:

//                if (!ConfigEntry.isAccessibilityEnabled(this)) {
//                    Toast.makeText(this, "请先开启辅助功能 " + getResources().getText(R.string.app_name), Toast.LENGTH_LONG).show();
//                    showEnableServiceHintDialog();
//                    return;
//                } else {
//                    intent.putExtra("frag_name", MineFragment.class.getName());
//                }
                break;
            case R.id.settings:
//                if (!ConfigEntry.isAccessibilityEnabled(this)) {
//                    Toast.makeText(this, "请先开启辅助功能 " + getResources().getText(R.string.app_name), Toast.LENGTH_LONG).show();
//                    showEnableServiceHintDialog();
//                    return;
//                } else {
//                    intent.putExtra("frag_name", SettingsFragment.class.getName());
//                }
                break;
            case R.id.about:
//                final AlertDialog.Builder builder0 = new AlertDialog.Builder(this);
//                builder0.setTitle("提示");
//                builder0.setMessage("为了方便您的使用，请选择您需要的帮助形式！");
//                builder0.setNegativeButton("文字介绍", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                        intent.putExtra("frag_name", AboutFragment.class.getName());
//                        intent.putExtra("url", NetUtils.HELP_URL);
//                        startActivity(intent);
//                    }
//                }).setPositiveButton("视频介绍", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//
//                        intent.putExtra("frag_name", AboutFragment.class.getName());
//                        intent.putExtra("url", NetUtils.VIEDO_URL);
//                        startActivity(intent);
//                    }
//                });
//
//                Dialog noticeDialog0 = builder0.create();
//                noticeDialog0.show();

                return;
            case R.id.vipbtn:
                MobclickAgent.onEvent(this, "clickvip0");
                AlertDialog.Builder builder = new AlertDialog.Builder(QiangHongBaoActivity.this);
                builder.setIcon(R.drawable.logo_small);
                builder.setTitle("请选择套餐:\n(充值成功后请重新启动应用)");
                final String[] types = {"  15元/月", "  40元/3月", "  80元/半年", "  150元/年", "  友情赞助1元"};
                builder.setItems(types, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, final int which) {
                        if (GlobalConfig.isDebug) {
                            Log.d(GlobalConfig.TAG, "pay dialog select = " + which);
                        }

//                        if (!User.isLogin) {
//                            User.login(getApplicationContext(), new CallBack() {
//                                @Override
//                                public void run(String content) {
//                                    mainHandler.post(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            showPayD(which, types);
//                                        }
//                                    });
//                                }
//                            }, null);
//                        } else {
//                            showPayD(which, types);
//                        }
                    }
                });
                builder.show();
                return;
            case R.id.share:
                Util.share(this);
                return;
            default:
                break;
        }
//        startActivity(intent);
    }

    private void showEnableServiceHintDialog() {

        mEnableServiceHintDialog = new Dialog(this, R.style.selectorDialog);
        mEnableServiceHintDialog.setContentView(R.layout.enable_service_hint_dialog);
        mEnableServiceHintDialog.findViewById(R.id.icon).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivityForResult(sSettingsIntent, 0x123);
                mEnableServiceHintDialog.dismiss();
            }
        });
        mEnableServiceHintDialog.findViewById(R.id.parent).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mEnableServiceHintDialog.dismiss();
            }
        });

        LayoutParams lay = mEnableServiceHintDialog.getWindow().getAttributes();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Rect rect = new Rect();
        View view = getWindow().getDecorView();
        view.getWindowVisibleDisplayFrame(rect);
        lay.height = dm.heightPixels - rect.top;
        lay.width = dm.widthPixels;

        mEnableServiceHintDialog.setCanceledOnTouchOutside(true);
        mEnableServiceHintDialog.show();
    }

    static long lastBack = System.currentTimeMillis();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - lastBack < 2000) {
                return super.onKeyDown(keyCode, event);
            } else {
                lastBack = System.currentTimeMillis();
                Toast.makeText(this, "需退出请再按一次返回", Toast.LENGTH_SHORT).show();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    AdView adView;
    /**
     * 百度广告
     */
    private void adbanner(){
        // 默认请求http广告，若需要请求https广告，请设置AdSettings.setSupportHttps为true
        // AdSettings.setSupportHttps(true);

        // 代码设置AppSid，此函数必须在AdView实例化前调用
        // AdView.setAppSid("debug");

        // 设置'广告着陆页'动作栏的颜色主题
        // 目前开放了七大主题：黑色、蓝色、咖啡色、绿色、藏青色、红色、白色(默认) 主题
        AppActivity
                .setActionBarColorTheme(AppActivity.ActionBarColorTheme.ACTION_BAR_WHITE_THEME);
        // 另外，也可设置动作栏中单个元素的颜色, 颜色参数为四段制，0xFF(透明度, 一般填FF)DE(红)DA(绿)DB(蓝)
        // AppActivity.getActionBarColorTheme().set[Background|Title|Progress|Close]Color(0xFFDEDADB);


        // 创建广告View
        String adPlaceId = "5531992"; //  重要：请填上您的广告位ID，代码位错误会导致无法请求到广告
        adView = new AdView(this, adPlaceId);
        // 设置监听器
        adView.setListener(new AdViewListener() {
            public void onAdSwitch() {
                Log.w("", "onAdSwitch");
            }

            public void onAdShow(JSONObject info) {
                // 广告已经渲染出来
                Log.w("", "onAdShow " + info.toString());
            }

            public void onAdReady(AdView adView) {
                // 资源已经缓存完毕，还没有渲染出来
                Log.w("", "onAdReady " + adView);
            }

            public void onAdFailed(String reason) {
                Log.w("", "onAdFailed " + reason);
            }

            public void onAdClick(JSONObject info) {
                // Log.w("", "onAdClick " + info.toString());

            }

            @Override
            public void onAdClose(JSONObject arg0) {
                Log.w("", "onAdClose");
            }
        });

        DisplayMetrics dm = new DisplayMetrics();
        ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
        int winW = dm.widthPixels;
        int winH = dm.heightPixels;
        int width = Math.min(winW, winH);
        int height = width * 3 / 20;
        // 将adView添加到父控件中(注：该父控件不一定为您的根控件，只要该控件能通过addView能添加广告视图即可)
        RelativeLayout.LayoutParams rllp = new RelativeLayout.LayoutParams(width, height);
        rllp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        parent.addView(adView, rllp);
    }

    InterstitialAd interAd;
    /**
     * 插屏广告
     */
    private void interstitialAd(){
        String adPlaceId = "5531994"; // 重要：请填上您的广告位ID，代码位错误会导致无法请求到广告
        interAd = new InterstitialAd(this, adPlaceId);
        interAd.setListener(new InterstitialAdListener() {

            @Override
            public void onAdClick(InterstitialAd arg0) {
                Log.i("InterstitialAd", "onAdClick");
            }

            @Override
            public void onAdDismissed() {
                Log.i("InterstitialAd", "onAdDismissed");
                interAd.loadAd();
            }

            @Override
            public void onAdFailed(String arg0) {
                Log.i("InterstitialAd", "onAdFailed");
            }

            @Override
            public void onAdPresent() {
                Log.i("InterstitialAd", "onAdPresent");
            }

            @Override
            public void onAdReady() {
                Log.i("InterstitialAd", "onAdReady");
            }

        });
        interAd.loadAd();
//        interAd.showAd(QiangHongBaoActivity.this);
    }
}
